import 'dart:async';

import 'package:chatgreat/bloc/payment_bloc.dart';
import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/logger.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/helper/platform.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/chat/markdown.dart';
import 'package:chatgreat/page/component/enhanced_button.dart';
import 'package:chatgreat/page/component/item_selector_search.dart';
import 'package:chatgreat/page/component/loading.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api/payment.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:go_router/go_router.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:tobias/tobias.dart';
// import 'package:fluwx/fluwx.dart' as fluwx;

import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';


import '../../helper/purchase_pay.dart';


/// 内购vip
class PaymentScreen extends StatefulWidget {
  final SettingRepository setting;
  const PaymentScreen({super.key, required this.setting});

  @override
  State<PaymentScreen> createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {

  Function()? _cancelLoading;

  final ScrollController _scrollController = ScrollController();
  int _currentIndex = 0; // 当前选择商品下标

  var inHours = 0.obs;
  var inMinutes = 0.obs;
  var inSeconds = 0.obs;

  Timer? timer;
  // 支付 ID
  String? paymentId;

  // ProductDetails? selectedProduct;
  PaymentProduct? selectedProduct;


  DateTime? _lastPressedTime;

  @override
  void initState() {
    PurchasePay().type = 1;
    PurchasePay().context = context;
    PurchasePay().onClosePaymentLoadingEvent = () {
      _closePaymentLoading();
    };
    PurchasePay().clearPendingPurchases();

    // 加载支付产品列表
    context.read<PaymentBloc>().add(PaymentLoadAppleProducts());
    super.initState();

    // 使用Timer更新剩余时间
    timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      // 获取当前时间
      final now = DateTime.now();
      // 获取今天的23:59:59
      final todayEnd = DateTime(now.year, now.month, now.day, 23, 59, 59, 999);
      final remaining = todayEnd.difference(DateTime.now());
      inHours.value = remaining.inHours;
      inMinutes.value = remaining.inMinutes % 60;
      inSeconds.value = remaining.inSeconds % 60;
      // 如果已经过了今天的时间，停止计时器
      if (remaining.isNegative) {
        timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    if (timer != null) {
      timer!.cancel();
    }
    super.dispose();
    print('--------------------> 释放支付');
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/bg1.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          title: const Text(
            '开通会员',
            style: TextStyle(
              fontSize: 18,
            ),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: customColors.weakLinkColor,
            ),
            onPressed: () {
              if (context.canPop()) {
                context.pop();
              } else {
                context.go(Ability().homeRoute);
              }
            },
          ),
          actions: [
            TextButton(
              onPressed: () {
                showErrorMessage('未查询到需要恢复的订单');
                return;

                _startPaymentLoading();
                InAppPurchase.instance.restorePurchases();
              },
              child: Text(
                "恢复购买",
                style: TextStyle(color: customColors.weakLinkColor),
              ),
            ),
          ],
        ),
        backgroundColor: Colors.transparent,
        body: BackgroundContainer(
          setting: widget.setting,
          enabled: false,
          child: SingleChildScrollView(
            // physics: const ClampingScrollPhysics(),
            child: Container(
              padding: const EdgeInsets.all(10),
              child: BlocConsumer<PaymentBloc, PaymentState>(
                listener: (context, state) {
                  if (state is PaymentAppleProductsLoaded) {
                    if (state.localProducts.isEmpty) {
                      showErrorMessage('暂无可购买的产品');
                    } else {
                      final recommends = state.localProducts;
                      if (recommends.isNotEmpty && !state.loading) {
                        setState(() {
                          if (state.localProducts.isNotEmpty) {
                            var firstProduct = state.localProducts.first;
                            selectedProduct = firstProduct;
                          }
                        });
                      }
                    }
                  }
                },
                buildWhen: (previous, current) =>
                    current is PaymentAppleProductsLoaded,
                builder: (context, state) {
                  if (state is! PaymentAppleProductsLoaded) {
                    return const Center(child: LoadingIndicator());
                  }
                  return Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            width: 110.w,
                            padding:
                                const EdgeInsets.only(bottom: 18.5, top: 18.5),
                            decoration: BoxDecoration(
                              color: const Color(0xFF21222F),
                              borderRadius: BorderRadius.circular(11),
                            ),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                imgWidget(44, 32, 'jianduanneihe'),
                                const SizedBox(height: 17.5),
                                MyTextSingle('AI尖端内核', 14, Colors.white,
                                    FontWeight.w500),
                                const SizedBox(height: 4),
                                MyTextSingle(
                                    '实时永久更新',
                                    12,
                                    Colors.white.withOpacity(0.6),
                                    FontWeight.w500),
                              ],
                            ),
                          ),
                          Container(
                            width: 110.w,
                            padding:
                                const EdgeInsets.only(bottom: 18.5, top: 18.5),
                            decoration: BoxDecoration(
                              color: const Color(0xFF21222F),
                              borderRadius: BorderRadius.circular(11),
                            ),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                imgWidget(44, 32, 'jianduanneihe'),
                                const SizedBox(height: 17.5),
                                MyTextSingle('深度算法加持', 14, Colors.white,
                                    FontWeight.w500),
                                const SizedBox(height: 4),
                                MyTextSingle(
                                    '提供满意回答',
                                    12,
                                    Colors.white.withOpacity(0.6),
                                    FontWeight.w500),
                              ],
                            ),
                          ),
                          Container(
                            width: 110.w,
                            padding:
                                const EdgeInsets.only(bottom: 18.5, top: 18.5),
                            decoration: BoxDecoration(
                              color: const Color(0xFF21222F),
                              borderRadius: BorderRadius.circular(11),
                            ),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                imgWidget(44, 32, 'jianduanneihe'),
                                const SizedBox(height: 17.5),
                                MyTextSingle('生图操作无门槛', 14, Colors.white,
                                    FontWeight.w500),
                                const SizedBox(height: 4),
                                MyTextSingle(
                                    '更无需排队',
                                    12,
                                    Colors.white.withOpacity(0.6),
                                    FontWeight.w500),
                              ],
                            ),
                          )
                        ],
                      ),
                      const SizedBox(height: 33),
                      Row(
                        children: [
                          imgWidget(45, 45, 'neihe'),
                          const SizedBox(width: 8),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              MyTextSingle('即刻升级Chat4o内核', 16, Colors.white,
                                  FontWeight.w400),
                              const SizedBox(height: 4),
                              MyTextSingle(
                                  '无限使用次数，回复更加智能',
                                  12,
                                  Colors.white.withOpacity(0.6),
                                  FontWeight.w400),
                            ],
                          )
                        ],
                      ),
                      const SizedBox(height: 25),
                      Row(
                        children: [
                          imgWidget(45, 45, 'jiesuo'),
                          const SizedBox(width: 8),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              MyTextSingle('高级特权一键解锁', 16, Colors.white,
                                  FontWeight.w400),
                              const SizedBox(height: 4),
                              MyTextSingle(
                                  '服务器响应速度提升，提问字数限制解除',
                                  12,
                                  Colors.white.withOpacity(0.6),
                                  FontWeight.w400),
                            ],
                          )
                        ],
                      ),
                      const SizedBox(height: 25),
                      Row(
                        children: [
                          imgWidget(45, 45, 'moxing'),
                          const SizedBox(width: 8),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              MyTextSingle('畅享行业顶尖AI模型', 16, Colors.white,
                                  FontWeight.w400),
                              const SizedBox(height: 4),
                              MyTextSingle(
                                  '超强参数，全面开启所有对话场景',
                                  12,
                                  Colors.white.withOpacity(0.6),
                                  FontWeight.w400),
                            ],
                          )
                        ],
                      ),
                      _subscribeWidget(state),
                      MyTextSingle(
                          '你选择的套餐正在超级折扣', 14, Colors.white, FontWeight.normal),
                      const SizedBox(height: 14),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          MyTextSingle(
                              '优惠倒计时：', 14, Colors.white, FontWeight.normal),
                          Obx(() => SizedBox(
                                width: 20,
                                height: 20,
                                child: MyTextSingle('${inHours.value}', 14,
                                    const Color(0xFF1CF1FF), FontWeight.normal,
                                    textAlign: TextAlign.end),
                              )),
                          MyTextSingle(
                              '小时', 14, Colors.white, FontWeight.normal),
                          Obx(() => SizedBox(
                                width: 20,
                                height: 20,
                                child: MyTextSingle('${inMinutes.value}', 14,
                                    const Color(0xFF1CF1FF), FontWeight.normal,
                                    textAlign: TextAlign.center),
                              )),
                          MyTextSingle(
                              '分', 14, Colors.white, FontWeight.normal),
                          Obx(() => SizedBox(
                                width: 20,
                                height: 20,
                                child: MyTextSingle('${inSeconds.value}', 14,
                                    const Color(0xFF1CF1FF), FontWeight.normal,
                                    textAlign: TextAlign.center),
                              )),
                          MyTextSingle(
                              '秒', 14, Colors.white, FontWeight.normal),
                        ],
                      ),
                      const SizedBox(height: 18),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 10),
                        child: EnhancedButton(
                          height: 48,
                          title: '立即开通',
                          onPressed: () async {
                            createPayEvent(state);
                          },
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            TextButton(
                                child: MyTextWeight(
                                    '用户协议',
                                    14,
                                    Colors.white.withOpacity(0.6),
                                    FontWeight.w400),
                                onPressed: () {
                                  context.push(Uri(
                                      path: '/web-view-page',
                                      queryParameters: {
                                        'title': '用户协议',
                                        'url':
                                            'https://chatgreatgopro.captainfeng.fun//#/agreementInfo?id=1'
                                      }).toString());
                                }),
                            TextButton(
                                child: MyTextWeight(
                                    '隐私协议',
                                    14,
                                    Colors.white.withOpacity(0.6),
                                    FontWeight.w400),
                                onPressed: () {
                                  context.push(Uri(
                                      path: '/web-view-page',
                                      queryParameters: {
                                        'title': '隐私协议',
                                        'url':
                                            'https://chatgreatgopro.captainfeng.fun//#/agreementInfo?id=2'
                                      }).toString());
                                }),
                          ],
                        ),
                      ),
                      if (state.note != null)
                        SizedBox(
                          width: double.infinity,
                          child: Markdown(
                            data: state.note!,
                            textStyle: TextStyle(
                              color: customColors.paymentItemTitleColor
                                  ?.withOpacity(0.6),
                              fontSize: 12,
                            ),
                          ),
                        ),
                    ],
                  );
                },
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 订阅时长视图
  Widget _subscribeWidget(state) {
    return Container(
      width: double.infinity,
      height: 122,
      margin: const EdgeInsets.only(top: 36, bottom: 22),
      child: GridView.count(
        crossAxisCount: 1,
        childAspectRatio: 122 / 95,
        scrollDirection: Axis.horizontal,
        mainAxisSpacing: 10,
        padding: const EdgeInsets.only(left: 12, right: 12),
        controller: _scrollController,
        children: _getWidgetList(state),
      ),
    );
  }

  /// 获取widget视图
  List<Widget> _getWidgetList(PaymentAppleProductsLoaded state) {
    List<Widget> widgets = [];
    for (int i = 0; i < state.localProducts.length; i++) {
      PaymentProduct model = state.localProducts[i];
      widgets.add(_itemWidget(model, i));
    }
    if (widgets.isEmpty) {
      widgets.add(Container());
    }
    return widgets;
  }

  /// item视图
  Widget _itemWidget(PaymentProduct model, int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _currentIndex = index;
          selectedProduct = model;
        });
      },
      child: Stack(
        children: <Widget>[
          Positioned(
              top: 0,
              left: 0,
              right: 0,
              bottom: 9,
              child: Container(
                decoration: BoxDecoration(
                  color: const Color(0xFF21222F),
                  borderRadius: BorderRadius.circular(10),
                  image: _currentIndex == index
                      ? const DecorationImage(
                          image: AssetImage('images/taocan1.png'),
                          fit: BoxFit.fill,
                        )
                      : const DecorationImage(
                          image: AssetImage('images/taocan0.png'),
                          fit: BoxFit.fill,
                        ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    const SizedBox(height: 1),
                    Text(model.name ?? '-',
                        style: const TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.normal,
                            color: Colors.white)),
                    const SizedBox(height: 20),
                    Text(
                        isNotBlank('${model.price}')
                            ? '${model.prefix}${getNumByValueDouble(model.price, 0)}'
                            : '${model.prefix}-',
                        style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w500,
                            color: Colors.white)),
                    Offstage(
                      offstage:
                          isBlank('${model.orgPrice}') || model.orgPrice == 0,
                      child: Container(
                        margin: const EdgeInsets.only(top: 2),
                        child: Text(
                          isNotBlank('${model.orgPrice}')
                              ? '原价${model.prefix}${getNumByValueDouble(model.orgPrice, 0)}'
                              : '原价${model.prefix}-',
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.4),
                            decoration: TextDecoration.lineThrough,
                            decorationColor: Colors.white.withOpacity(0.4),
                            fontSize: 12.0,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              )),
          isBlank('${model.giveDiamond}') || model.giveDiamond == 0
              ? const SizedBox(width: 0)
              : Positioned(
                  bottom: 0,
                  left: 8,
                  right: 8,
                  child: Container(
                    padding: const EdgeInsets.only(
                        left: 4, right: 4, top: 2, bottom: 2),
                    decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(9))),
                    child: Text(
                      "赠送${model.giveDiamond}积分",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 10,
                          color: _currentIndex == index
                              ? const Color(0xFF227DE1)
                              : const Color(0xFF9C9B9B)),
                    ),
                  ))
        ],
      ),
    );
  }

  Future<void> createPayEvent(PaymentAppleProductsLoaded state) async {
    if (state.loading) {
      showErrorMessage('产品加载中，请稍后');
      return;
    }
    if (selectedProduct == null) {
      showErrorMessage('请选择购买的产品');
      return;
    }

    // 检查是否点击按钮拉起的支付
    PurchasePay().paymenting = true;

    // 拉起支付
    if (PlatformTool.isIOS()) {
      _startPaymentLoading();
      try {
        await createAppApplePay();
      } catch (e) {
        _closePaymentLoading();
        // ignore: use_build_context_synchronously
        showErrorMessage(resolveError(context, e));
      }
    }
  }

  /// 关闭支付中的 loading
  void _closePaymentLoading() {
    paymentId = null;
    if (_cancelLoading != null) {
      _cancelLoading!();
      _cancelLoading = null;
    }
  }

  /// 开始支付中的 loading
  void _startPaymentLoading() {
    _cancelLoading = BotToast.showCustomLoading(
      toastBuilder: (cancel) {
        return LoadingIndicator(
          message: AppLocale.processingWait.getString(context),
        );
      },
      allowClick: false,
      duration: const Duration(seconds: 120),
        backgroundColor: Colors.black.withOpacity(0.4)
    );
  }

  /// 创建苹果应用内支付
  Future<void> createAppApplePay() async {
    print("请求商品id ${selectedProduct?.appleId}");
    var productId = selectedProduct?.appleId ?? '1';
    List<String> outProducts = [productId];

    final bool available = await InAppPurchase.instance.isAvailable();
    if (!available) {
      _closePaymentLoading();
      throw showErrorMessage("无法连接到商店，请稍候重试");
    }

    //开始购买
    print("连接成功-开始查询全部商品");
    List<String> kIds = outProducts;
    final ProductDetailsResponse response =
        await InAppPurchase.instance.queryProductDetails(kIds.toSet());
    print("商品获取结果  ${response.productDetails}");
    if (response.productDetails.isEmpty) {
      _closePaymentLoading();
      showErrorMessage('没有获取到商品信息，请联系管理员');
      return;
    }
    if (response.notFoundIDs.isNotEmpty) {
      _closePaymentLoading();
      throw showErrorMessage("无法找到指定的商品");
    }

    // 处理查询到的商品列表
    List<ProductDetails> products = response.productDetails;
    print("products ==== " + products.length.toString());
    if (products.isEmpty) {
      _closePaymentLoading();
      throw showErrorMessage("无法找到指定的商品");
    }

    var chooseProduct =
        products.firstWhere((product) => product.id == productId);
    print(
        "一切正常，开始购买,信息如下：title: ${chooseProduct.title}  desc:${chooseProduct.description} "
        "price:${chooseProduct.price}  currencyCode:${chooseProduct.currencyCode}  currencySymbol:${chooseProduct.currencySymbol}");

    // 发起 Apple 支付
    InAppPurchase.instance.buyConsumable(
      purchaseParam: PurchaseParam(productDetails: chooseProduct),
    );
  }

  /// 处理 android 支付
  void handlePaymentForAndroid(
    PaymentAppleProductsLoaded state,
    BuildContext context,
    CustomColors customColors,
  ) {
    final localProduct =
        state.localProducts.firstWhere((e) => e.id == selectedProduct!.id);
    final enableStripe = Ability().enableStripe;
    openListSelectDialog(
      context,
      <SelectorItem>[
        if (Ability().enableWechatPay)
          SelectorItem(
            const PaymentMethodItem(
              title: Text('微信支付'),
              image: 'assets/wechat-pay.png',
            ),
            'wechat-pay',
          ),
        if (Ability().enableOtherPay)
          SelectorItem(
            const PaymentMethodItem(
              title: Text('支付宝'),
              image: 'assets/zhifubao.png',
            ),
            'alipay',
          ),
        if (enableStripe)
          SelectorItem(
            PaymentMethodItem(
              title: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('Stripe'),
                  const SizedBox(width: 5),
                  Text(
                    '(${localProduct.price})',
                    style: TextStyle(
                      color:
                          customColors.paymentItemTitleColor?.withOpacity(0.5),
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
              image: 'assets/stripe.png',
            ),
            'stripe',
          ),
      ],
      (value) {
        _startPaymentLoading();

        if (value.value == 'alipay') {
          createAppAlipay().onError((error, stackTrace) {
            _closePaymentLoading();
            showErrorMessageEnhanced(context, error!);
          });
        } else if (value.value == 'wechat-pay') {
          createWechatPayment(localProduct);
        }

        return true;
      },
      title: '请选择支付方式',
      heightFactor: 0.3,
    );
  }

  /// 获取当前支付来源参数
  String paymentSource() {
    if (PlatformTool.isWeb()) {
      return 'web';
    } else if (PlatformTool.isIOS() || PlatformTool.isAndroid()) {
      return 'app';
    }
    return 'pc';
  }

  /// 创建微信支付
  Future<void> createWechatPayment(PaymentProduct product) async {
    try {
      final created = await APIServer().createWechatPayment(
        productId: '${product.id ?? 0}',
        source: paymentSource(),
      );
      paymentId = created.paymentId;

      if (PlatformTool.isAndroid() || PlatformTool.isIOS()) {
        // await fluwx.payWithWeChat(
        //   appId: created.appId!,
        //   partnerId: created.partnerId!,
        //   prepayId: created.prepayId!,
        //   packageValue: created.package!,
        //   nonceStr: created.noncestr!,
        //   timeStamp: int.parse(created.timestamp!),
        //   sign: created.sign!,
        // );
      } else {
        openDialog(
          // ignore: use_build_context_synchronously
          context,
          builder: Builder(builder: (context) {
            return Container(
              alignment: Alignment.center,
              height: 250,
              width: 220,
              margin: const EdgeInsets.only(top: 20),
              child: Column(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: QrImageView(
                      data: created.codeUrl!,
                      version: QrVersions.auto,
                      size: 200,
                      backgroundColor: Colors.white,
                    ),
                  ),
                  const SizedBox(height: 10),
                  const Text(
                    '请使用微信扫码支付',
                    style: TextStyle(
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            );
          }),
          onSubmit: () {
            _startPaymentLoading();
            APIServer().queryPaymentStatus(created.paymentId).then((resp) {
              if (resp.success) {
                showSuccessMessage(resp.note ?? '支付成功');
                _closePaymentLoading();
              } else {
                // 支付失败，延迟 5s 再次查询支付状态
                Future.delayed(const Duration(seconds: 5), () async {
                  try {
                    final value =
                        await APIServer().queryPaymentStatus(created.paymentId);

                    if (value.success) {
                      showSuccessMessage(value.note ?? '支付成功');
                    } else {
                      showErrorMessage('支付未完成，我们接收到的状态为：${value.note}');
                    }
                  } catch (e) {
                    // ignore: use_build_context_synchronously
                    showErrorMessage(resolveError(context, e));
                  } finally {
                    _closePaymentLoading();
                  }
                });
              }
            });

            return true;
          },
          confirmText: '已完成支付',
          barrierDismissible: false,
        );
      }
    } on Exception catch (e) {
      // ignore: use_build_context_synchronously
      showErrorMessageEnhanced(context, e);
    } finally {
      _closePaymentLoading();
    }
  }

  /// 创建其它付款（App）
  Future<void> createAppAlipay() async {
    // 其它支付
    final created = await APIServer().createOtherPay(
      '${selectedProduct!.id}',
      source: 'app',
    );
    paymentId = created.paymentId;

    // 沙箱环境支持
    final env = created.sandbox ? AliPayEvn.SANDBOX : AliPayEvn.ONLINE;

    // 调起其它支付
    final aliPayRes = await aliPay(
      created.params,
      evn: env,
    ).whenComplete(() => _closePaymentLoading());
    print("=================");
    print(aliPayRes);
    print(aliPayRes["resultStatus"]);
    if (aliPayRes['resultStatus'] == '9000') {
      await APIServer().otherPayClientConfirm(
        aliPayRes.map((key, value) => MapEntry(key.toString(), value)),
      );

      showSuccessMessage('购买成功');
    } else {
      switch (aliPayRes['resultStatus']) {
        case 8000: // fall through
        case 6004:
          showErrorMessage('支付处理中，请稍后查看购买历史确认结果');
          break;
        case 4000:
          showErrorMessage('支付失败');
          break;
        case 5000:
          showErrorMessage('重复请求');
          break;
        case 6001:
          showErrorMessage('支付已取消');
          break;
        case 6002:
          showErrorMessage('网络连接出错');
          break;
        default:
          showErrorMessage('支付失败');
      }
    }
    print("-----------------");
  }

}

/// 支付方式选择项
class PaymentMethodItem extends StatelessWidget {
  final Widget title;
  final String? image;

  const PaymentMethodItem({super.key, required this.title, this.image});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (image != null) ...[
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Image.asset(
              image!,
              width: 20,
              height: 20,
            ),
          ),
          const SizedBox(width: 10),
        ],
        title,
      ],
    );
  }
}
